package com.crawler.harbour.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

public class HtmlCleanerUtils {

	public static TagNode getNodeByXpath(TagNode node, String xpath) throws XPatherException{
		Object obj = getNodeObjectByXpath(node, xpath);
		return (TagNode)obj;
	}
	
	public static String getNodeAttributeByXpath(TagNode node, String xpath) throws XPatherException{
		Object obj = getNodeObjectByXpath(node, xpath);
		return obj.toString();
	}
	
	public static Object getNodeObjectByXpath(TagNode node, String xpath) throws XPatherException{
		Object[] objs = node.evaluateXPath(xpath);
		if(objs.length>0){
			return objs[0];
		}else{
			return null;
		}
	} 
	
	public static List<TagNode> getNodesByXpath(TagNode node, String xpath) throws XPatherException{
		List<TagNode> nodeList = new ArrayList<TagNode>();
		Object[] objs = node.evaluateXPath(xpath);
		for(Object o:objs){
			nodeList.add((TagNode)o);
		}
		return nodeList;
	}
	
	public static List<TagNode> getNodesByXpath(String source, String xpath) throws IOException, XPatherException{
		List<TagNode> nodes = new ArrayList<TagNode>();
		HtmlCleaner hc = new HtmlCleaner();
		TagNode body = hc.clean(source);
		nodes = getNodesByXpath(body, xpath);
		return nodes;
	}
	
	public static String getNodeText(TagNode rootNode,String xpath) {
		if(rootNode==null) return null;
		try {
			TagNode targetNode=getNodeByXpath(rootNode, xpath);
			if(targetNode==null) return null;
			return ReduceHtml2Text.removeHtmlTag(targetNode.getText().toString());
//			return targetNode.getText().toString().replace("&nbsp;", "").trim();
		} catch (XPatherException e) {
			return null;
		}
	}
	
}
